#!/usr/bin/python
'''
prints desired sam files from a divided ham file.
'''
import sys
import ham
import h5py
import logging
import numpy as np

logging.basicConfig(level=logging.INFO, format='[%(levelname)s] (%(threadName)-10s) %(message)s', )
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s', )

# parameters.
ham_ant_file = sys.argv[1]
ham_file1 = sys.argv[2]
ham_file2 = sys.argv[3]
sam_file1 = sys.argv[4]
sam_file2 = sys.argv[5]

# open ham objects for reading.
ham_ant_obj = ham.HamAnnotate(ham_ant_file, read=True)
ham_a_obj = ham.HamFile(ham_file1, read=True)
ham_b_obj = ham.HamFile(ham_file2, read=True)

# load indices into memory.
logging.info("loading indicies into memory.")
ant_a, ant_b = ham_ant_obj.load_annotation()

# get pointers to ham data.
logging.info("loading ham files into memory.")
#ham_a = ham_a_obj.load_complete()
#ham_b = ham_b_obj.load_complete()
ham_a = ham_a_obj.data[0:10000]
ham_b = ham_b_obj.data[0:10000]

# open sam files.
sam_out_1 = open(sam_file1, "wb")
sam_out_2 = open(sam_file2, "wb")

# find double unique partners.
logging.info("searching for unique pairs.")
for i in range(ham_a.size):
	
	# look for uniquely mapped.
	if ant_a[i]['TYPE'] != 1: continue
	
	# look for noted partner.
	if ant_a[i]['MIDX'] == -1: continue
	
	# ensure partner is unique.
	id2 = ant_a[i]['MIDX']
	if ant_b[id2]['TYPE'] != 1: continue

	
	# build txt.
	txt1 = "%s\t%i\t%s\t%i\t%i\t%s\t%s\t%i\t%i\t%s\t%s\t%s\n" % \
		(ham_a[i]['QNAME'], ham_a[i]['FLAG'], ham_a[i]['RNAME'], \
		ham_a[i]['POS'], ham_a[i]['MAPQ'], ham_a[i]['CIGAR'], \
		ham_a[i]['MRNM'], ham_a[i]['MPOS'], ham_a[i]['ISIZE'],\
		ham_a[i]['SEQ'], ham_a[i]['QUAL'], ham_a[i]['OPTIONAL'])
	txt2 = "%s\t%i\t%s\t%i\t%i\t%s\t%s\t%i\t%i\t%s\t%s\t%s\n" % \
		(ham_b[id2]['QNAME'], ham_b[id2]['FLAG'], ham_b[id2]['RNAME'], \
		ham_b[id2]['POS'], ham_b[id2]['MAPQ'], ham_b[id2]['CIGAR'], \
		ham_b[id2]['MRNM'], ham_b[id2]['MPOS'], ham_b[id2]['ISIZE'],\
		ham_b[id2]['SEQ'], ham_b[id2]['QUAL'], ham_b[id2]['OPTIONAL'])
		
	# write text.
	sam_out_1.write(txt1)
	sam_out_2.write(txt2)
	

# close pointers.
sam_out_1.close()
sam_out_2.close()

ham_a_obj.close()
ham_b_obj.close()
ham_ant_obj.close()

